<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>课堂平台 - {{ user_info.name }}</title>
    <style>
        @import url('https://fonts.googleapis.com/css2?family=Noto+Sans+SC:wght@400;500;700&display=swap');
        :root {
            --primary-color: #007bff;
            --teacher-color: #28a745;
            --bg-color: #f4f7f6;
            --panel-bg-color: #ffffff;
            --text-color: #333;
            --border-color: #e0e0e0;
            --header-bg: #f8f9fa;
        }
        body { font-family: 'Noto Sans SC', sans-serif; background-color: var(--bg-color); color: var(--text-color); margin: 0; height: 100vh; overflow: hidden; }
        .main-container { display: flex; height: 100%; width: 100%; }
        .panel { display: flex; flex-direction: column; margin: 10px; border-radius: 12px; box-shadow: 0 4px 15px rgba(0, 0, 0, 0.08); overflow: hidden; background-color: var(--panel-bg-color); }
        .content-panel { flex: 2; display: flex; flex-direction: column; }
        .chat-panel { flex: 1; min-width: 320px; }
        .panel-header { padding: 15px 20px; border-bottom: 1px solid var(--border-color); background-color: var(--header-bg); display: flex; justify-content: space-between; align-items: center; }
        .panel-header h2 { margin: 0; font-size: 18px; font-weight: 500; }
        .panel-content { padding: 15px; overflow-y: auto; flex-grow: 1; }

        /* --- Assignments Panel --- */
        .assignments-panel { flex: 3; display: flex; flex-direction: column; }
        .assignments-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(280px, 1fr)); gap: 15px; }
        .assignment-card { border: 1px solid var(--border-color); border-radius: 8px; transition: box-shadow 0.3s; cursor: pointer; background: #fff; display: flex; flex-direction: column; }
        .assignment-card:hover { box-shadow: 0 4px 12px rgba(0,0,0,0.08); }
        .assignment-card-content { padding: 15px; flex-grow: 1; }
        .assignment-card-content h3 { margin: 0 0 10px; font-size: 1.1rem; }
        .assignment-card-footer { border-top: 1px solid var(--border-color); padding: 10px 15px; background: var(--header-bg); }
        .status-badge { display: inline-block; padding: 4px 10px; border-radius: 12px; font-size: 0.8rem; font-weight: 500; color: #fff; }
        .status-new, .status-unsubmitted { background-color: #6c757d; }
        .status-published, .status-submitted { background-color: #ffc107; }
        .status-ended { background-color: #dc3545; }
        .status-grading { background-color: #17a2b8; }
        .status-graded { background-color: var(--teacher-color); }
        .score-badge { font-weight: 700; color: var(--teacher-color); font-size: 1.1rem; }

        #new-assignment-btn { background-color: var(--teacher-color); color: white; border: none; padding: 8px 15px; border-radius: 5px; cursor: pointer; font-weight: 500; }

        /* --- Files Panel --- */
        .files-panel { flex: 1; min-height: 150px; display: flex; flex-direction: column; }
        .files-panel table { width: 100%; border-collapse: collapse; }
        .files-panel th, .files-panel td { padding: 8px 10px; text-align: left; border-bottom: 1px solid #f0f0f0; }
        .files-panel th { font-size: 14px; color: #666; }
        .files-panel td { font-size: 15px; }
        .files-panel td a { color: var(--primary-color); text-decoration: none; }

        /* --- Chat Panel (Reused) --- */
        /* ... styles omitted for brevity ... */

        /* --- Modal Styles --- */
        .modal-overlay { position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: rgba(0,0,0,0.5); z-index: 1000; display: none; justify-content: center; align-items: center; }
        .modal-content { background: white; border-radius: 8px; padding: 25px; width: 90%; max-width: 700px; max-height: 90vh; display: flex; flex-direction: column; box-shadow: 0 5px 15px rgba(0,0,0,0.3); }
        .modal-header { display: flex; justify-content: space-between; align-items: center; border-bottom: 1px solid var(--border-color); padding-bottom: 10px; margin-bottom: 20px; }
        .modal-header h2 { margin: 0; }
        .modal-close { font-size: 2rem; font-weight: 300; cursor: pointer; border: none; background: none; }
        .modal-body { overflow-y: auto; display: grid; grid-template-columns: 1fr 1fr; gap: 20px; }
        .form-group { display: flex; flex-direction: column; }
        .form-group label { font-weight: 500; margin-bottom: 8px; }
        .form-group input, .form-group select, .form-group textarea { padding: 10px; border: 1px solid #ccc; border-radius: 5px; font-size: 1rem; font-family: inherit; }
        .form-group textarea { min-height: 150px; resize: vertical; }
        .form-group.full-span { grid-column: 1 / -1; }
        .ai-helper { display: flex; align-items: center; margin-top: 8px; }
        .ai-helper input { flex-grow: 1; border-radius: 5px 0 0 5px; }
        .ai-helper button { padding: 10px; border: none; background: var(--teacher-color); color: white; cursor: pointer; border-radius: 0 5px 5px 0; }
        .modal-footer { border-top: 1px solid var(--border-color); padding-top: 15px; margin-top: 20px; display: flex; justify-content: flex-end; gap: 10px; }
        .modal-footer button { padding: 10px 20px; border: none; border-radius: 5px; cursor: pointer; font-weight: 500; }
        #modal-save-btn { background: var(--primary-color); color: white; }
        #modal-delete-btn { background: #dc3545; color: white; }
        #modal-cancel-btn { background: #6c757d; color: white; }
    </style>
</head>
<body>

    <div class="main-container">
        <div class="panel content-panel">

            <div class="assignments-panel">
                <div class="panel-header">
                    {% if user_info.role == 'teacher' %}
                        <h2>作业管理</h2>
                        <button id="new-assignment-btn" onclick="openAssignmentModal()">+ 新建作业</button>
                    {% else %}
                        <h2>我的作业</h2>
                        <span>欢迎, {{ user_info.name }}</span>
                    {% endif %}
                </div>
                <div class="panel-content">
                    <div class="assignments-grid">
                        {% for assignment in assignments %} {# <-- Start of the 'for' loop #}
                        <div class="assignment-card" onclick="location.href='/assignment/{{ assignment.id }}'">
                            <div class="assignment-card-content">
                                <h3>{{ assignment.title }}</h3>
                                {% if user_info.role == 'teacher' %}
                                    <span class="status-badge status-{{ assignment.status }}">{{ assignment.status | replace('new', '新作业') | replace('published', '已发布') | replace('ended', '已截止') }}</span>
                                {% else %}
                                    <span class="status-badge status-{{ assignment.status }}">{{ assignment.status | replace('published', '进行中') | replace('ended', '已截止') }}</span>
                                {% endif %}
                            </div>
                            {% if user_info.role == 'student' %} {# <-- Start of the inner 'if' #}
                            <div class="assignment-card-footer">
                                {% if assignment.submission_status == 'unsubmitted' %}
                                    <span class="status-badge status-unsubmitted">未提交</span>
                                {% elif assignment.submission_status == 'submitted' %}
                                    <span class="status-badge status-submitted">已提交</span>
                                {% elif assignment.submission_status == 'grading' %}
                                    <span class="status-badge status-grading">批改中</span>
                                {% elif assignment.submission_status == 'graded' %}
                                    <span class="status-badge status-graded">已批改</span>
                                    <span class="score-badge" style="float: right;">{{ assignment.submission_score }} 分</span>
                                {% endif %}
                            </div>
                            {% endif %} {# <-- End of the inner 'if' #}
                        </div>
                        {% endfor %} {# <-- FIX: Added the missing endfor tag HERE #}
                    </div> {# <-- End of assignments-grid #}
                </div> {# <-- End of panel-content #}
            </div> {# <-- End of assignments-panel #}


            <div class="files-panel">
                <div class="panel-header">
                    <h2>文件分享</h2>
                    <a href="/logout" style="font-size: 14px; text-decoration: none;">退出登录</a>
                </div>
                <div class="panel-content" style="padding: 0 15px;">
                    <table>
                        <thead><tr><th>文件名</th><th>大小</th></tr></thead>
                        <tbody>
                            {% for file in shared_files %}
                            <tr>
                                <td><a href="/download/{{ file.name }}" target="_blank">{{ file.name }}</a></td>
                                <td>{{ file.size }}</td>
                            </tr>
                            {% else %}
                            <tr><td colspan="2" style="text-align: center; padding: 10px; color: #888;">暂无文件</td></tr>
                            {% endfor %} {# <-- Closing the 'for file in shared_files' loop #}
                        </tbody>
                    </table>
                </div>
            </div>

        </div>

        <div class="panel chat-panel" id="chat-panel-v3">
             <div class="panel-header"><h2>课堂研讨室</h2></div>
             <div id="user-list-container" style="padding: 10px 20px; border-bottom: 1px solid var(--border-color);">
                 <h3 style="margin: 0 0 8px 0; font-size: 14px; color: #555;">在线成员</h3>
                 <div id="user-list" style="display: flex; flex-wrap: wrap; gap: 8px;"></div>
             </div>
             <div class="panel-content" id="chat-box">
                 </div>
             <div class="chat-input" style="padding: 15px; border-top: 1px solid var(--border-color);">
                 <form id="message-form" style="display: flex;">
                     <input id="message-text" autocomplete="off" placeholder="输入消息..." style="flex-grow: 1; border: 1px solid var(--border-color); border-radius: 20px; padding: 10px 15px; font-size: 15px;">
                     <button type="submit" style="margin-left: 10px; padding: 10px 20px; border: none; background-color: var(--primary-color); color: white; border-radius: 20px; cursor: pointer; font-size: 15px;">发送</button>
                 </form>
             </div>
         </div>
    </div>

    {% if user_info.role == 'teacher' %}
    <div id="assignment-modal" class="modal-overlay">
        <div class="modal-content">
            <div class="modal-header">
                <h2 id="modal-title">新建作业</h2>
                <button class="modal-close" onclick="closeAssignmentModal()">&times;</button>
            </div>
            <form id="assignment-form" class="modal-body">
                <input type="hidden" id="assignment-id" value="">
                <div class="form-group"><label for="assignment-title">作业标题</label><input type="text" id="assignment-title" required></div>
                <div class="form-group">
                    <label for="assignment-grading-mode">批改方式</label>
                    <select id="assignment-grading-mode"><option value="manual">手动批改</option><option value="ai">AI 自动批改</option></select>
                </div>
                <div class="form-group full-span">
                    <label for="assignment-requirements">作业要求 (Markdown)</label>
                    <textarea id="assignment-requirements"></textarea>
                    <div class="ai-helper">
                        <input type="text" id="ai-req-prompt" placeholder="输入提示词, 让AI生成作业要求..."><button type="button" onclick="generateWithAI('requirements')">AI 生成</button>
                    </div>
                </div>
                <div class="form-group full-span">
                    <label for="assignment-rubric">得分点 (Markdown)</label>
                    <textarea id="assignment-rubric"></textarea>
                    <div class="ai-helper">
                        <input type="text" id="ai-rubric-prompt" placeholder="输入提示词, 让AI生成得分点..."><button type="button" onclick="generateWithAI('rubric')">AI 生成</button>
                    </div>
                </div>
                <div class="form-group">
                    <label for="assignment-status">作业状态</label>
                    <select id="assignment-status"><option value="new">新作业</option><option value="published">发布</option><option value="ended">截止</option></select>
                </div>
            </form>
            <div class="modal-footer">
                <button id="modal-delete-btn" onclick="deleteAssignment()" style="display: none; margin-right: auto;">删除作业</button>
                <button id="modal-cancel-btn" onclick="closeAssignmentModal()">取消</button>
                <button id="modal-save-btn" onclick="saveAssignment()">保存</button>
            </div>
        </div>
    </div>
    {% endif %}

    <script>
        const userInfo = {{ user_info | tojson }};

        // --- WebSocket Chat (V2.5 JS) ---
        const wsProtocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:';
        const ws = new WebSocket(`${wsProtocol}//${window.location.host}/ws`);
        const chatBox = document.getElementById('chat-box');
        const messageForm = document.getElementById('message-form');
        const messageInput = document.getElementById('message-text');
        const userListDiv = document.getElementById('user-list');

        function scrollToBottom() { chatBox.scrollTop = chatBox.scrollHeight; }
        function appendChatMessage(data) {
            const msgEl = document.createElement('div');
            const isSelf = data.sender === userInfo.name;
            const isTeacher = data.role === 'teacher';
            msgEl.className = `message ${isSelf ? 'self' : 'other'} ${isTeacher ? 'teacher' : ''}`;
            msgEl.innerHTML = `<div class="sender-info">${data.sender} <span class="timestamp">${data.timestamp}</span></div><div class="message-content">${data.message}</div>`;
            chatBox.appendChild(msgEl);
        }
        function appendSystemMessage(data) {
            const msgEl = document.createElement('div');
            msgEl.className = 'message system';
            msgEl.textContent = `--- ${data.message} ---`;
            chatBox.appendChild(msgEl);
        }
        function updateUserList(users) {
            userListDiv.innerHTML = '';
            users.forEach(user => {
                const tag = document.createElement('span');
                tag.className = `user-tag ${user.role === 'teacher' ? 'teacher' : ''}`; // Simplified class assignment
                tag.textContent = user.name;
                userListDiv.appendChild(tag);
            });
        }
        ws.onmessage = function(event) {
            const data = JSON.parse(event.data);
            switch (data.type) {
                case 'history':
                    chatBox.innerHTML = ''; data.data.forEach(appendChatMessage);
                    appendSystemMessage({ message: "以上是历史消息" }); break;
                case 'chat': appendChatMessage(data); break;
                case 'system': appendSystemMessage(data); break;
                case 'user_list': updateUserList(data.data); break;
            }
            scrollToBottom();
        };
        ws.onopen = () => appendSystemMessage({ message: "已连接" });
        ws.onclose = () => appendSystemMessage({ message: "连接已断开" });
        ws.onerror = () => appendSystemMessage({ message: "连接错误" });
        messageForm.addEventListener('submit', e => {
            e.preventDefault();
            if (messageInput.value) { ws.send(messageInput.value); messageInput.value = ''; }
        });

        // CSS for chat (inlined to keep it in one file)
        const chatStyle = document.createElement('style');
        chatStyle.innerHTML = `
            #user-list .user-tag { background-color: #f1f1f1; padding: 3px 8px; border-radius: 12px; font-size: 13px; }
            #user-list .user-tag.teacher { background-color: var(--teacher-color); color: white; font-weight: 500; }
            #chat-box { padding: 15px; }
            .message { margin-bottom: 12px; max-width: 85%; line-height: 1.5; }
            .message-content { padding: 8px 12px; border-radius: 18px; display: inline-block; word-wrap: break-word; } /* Added word-wrap */
            .message.other { float: left; clear: both; text-align: left; }
            .message.other .message-content { background-color: #e9ecef; color: var(--text-color); border-bottom-left-radius: 4px; }
            .message.self { float: right; clear: both; text-align: right;}
            .message.self .message-content { background-color: var(--primary-color); color: white; border-bottom-right-radius: 4px; }
            .message.teacher .message-content { background-color: var(--teacher-color); color: white; }
            .sender-info { font-size: 12px; color: #888; margin: 0 5px 4px; display: block; } /* Made sender-info block */
            /* Removed text-align: right from self sender-info as parent handles it */
            .message.system { text-align: center; color: #6c757d; font-size: 12px; width: 100%; clear: both; }
        `;
        document.head.appendChild(chatStyle);
        // --- End of Chat JS ---


        // --- Assignment Modal Logic (TEACHER ONLY) ---
        {% if user_info.role == 'teacher' %}
        const modal = document.getElementById('assignment-modal');
        const form = document.getElementById('assignment-form');
        const modalTitle = document.getElementById('modal-title');

        function openAssignmentModal(assignment = null) {
            form.reset();
            document.getElementById('assignment-id').value = '';
            document.getElementById('modal-delete-btn').style.display = 'none';

            if (assignment) {
                modalTitle.textContent = '编辑作业';
                document.getElementById('assignment-id').value = assignment.id;
                document.getElementById('assignment-title').value = assignment.title;
                document.getElementById('assignment-grading-mode').value = assignment.grading_mode;
                document.getElementById('assignment-requirements').value = assignment.requirements_md;
                document.getElementById('assignment-rubric').value = assignment.rubric_md;
                document.getElementById('assignment-status').value = assignment.status;
                document.getElementById('modal-delete-btn').style.display = 'block';
            } else {
                modalTitle.textContent = '新建作业';
            }
            modal.style.display = 'flex';
        }

        function closeAssignmentModal() { modal.style.display = 'none'; }

        async function saveAssignment() {
            const id = document.getElementById('assignment-id').value;
            const data = {
                title: document.getElementById('assignment-title').value,
                grading_mode: document.getElementById('assignment-grading-mode').value,
                requirements_md: document.getElementById('assignment-requirements').value,
                rubric_md: document.getElementById('assignment-rubric').value,
                status: document.getElementById('assignment-status').value,
            };
            const url = id ? `/api/assignments/${id}` : '/api/assignments';
            const method = id ? 'PUT' : 'POST';
            try {
                const response = await fetch(url, { method: method, headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(data), });
                if (response.ok) { location.reload(); } else { alert('保存失败: ' + (await response.text())); }
            } catch (err) { alert('保存出错: ' + err.message); }
        }

        async function deleteAssignment() {
            const id = document.getElementById('assignment-id').value;
            if (!id || !confirm('确定要删除这个作业吗？所有相关的学生提交都将被删除！')) return;
            try {
                const response = await fetch(`/api/assignments/${id}`, { method: 'DELETE' });
                if (response.ok) { location.reload(); } else { alert('删除失败: ' + (await response.text())); }
            } catch (err) { alert('删除出错: ' + err.message); }
        }

async function generateWithAI(type) {
            // 获取对应输入框的提示词
            const promptInputId = type === 'requirements' ? 'ai-req-prompt' : 'ai-rubric-prompt';
            let userPrompt = document.getElementById(promptInputId).value;

            if (!userPrompt) {
                alert('请输入AI提示词');
                return;
            }

            // *** 改进点：如果是生成评分标准，则附加上作业要求 ***
            if (type === 'rubric') {
                const requirementsText = document.getElementById('assignment-requirements').value;
                if (requirementsText) {
                    // 构建更丰富的提示词，包含作业要求
                    userPrompt = `请根据以下作业要求，生成评分标准。\n\n【作业要求】:\n${requirementsText}\n\n【生成评分标准的提示词】:\n${userPrompt}`;
                    console.log("Combined prompt for rubric:", userPrompt); // 可以在浏览器控制台查看组合后的提示词
                } else {
                    alert('请先填写作业要求，才能让AI更好地生成评分标准。');
                    return; // 如果没有作业要求，则阻止生成评分标准
                }
            }
            // *** 改进结束 ***

            const btn = event.target; // 获取触发事件的按钮
            btn.textContent = '生成中...';
            btn.disabled = true;

            try {
                // 判断模型类型 (简单启发式)
                const modelType = userPrompt.length > 50 ? 'thinking' : 'standard';

                const response = await fetch('/api/ai/generate_assignment', {
                     method: 'POST',
                     headers: { 'Content-Type': 'application/json' },
                     // 发送组合后的提示词 (userPrompt) 和模型类型
                     body: JSON.stringify({ prompt: userPrompt, model_type: modelType })
                });

                if (response.ok) {
                    const data = await response.json();
                    // 处理响应，检查预期的键或回退到原始文本
                    const requirements = data.requirements_md;
                    const rubric = data.rubric_md;
                    const rawText = data.text;

                    if (type === 'requirements') {
                        document.getElementById('assignment-requirements').value = requirements || rawText || "AI未能生成有效内容";
                    } else if (type === 'rubric') {
                        document.getElementById('assignment-rubric').value = rubric || rawText || "AI未能生成有效内容";
                    }
                } else {
                    alert('AI生成失败: ' + (await response.text()));
                }
            } catch (err) {
                alert('AI请求出错: ' + err.message);
            } finally {
                btn.textContent = 'AI 生成';
                btn.disabled = false;
            }
        }
        {% endif %}
    </script>

</body>
</html>